﻿using Microsoft.Extensions.DependencyInjection;
using ApiCoreProject.Model.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace ApiCoreProject.Dal
{
    public class BaseDal<T> : IDisposable, IBaseDal<T> where T : class, new()
    {
        private readonly BaseDBContext _context;

        /// <summary>
        /// 获得数据库上下文
        /// </summary>
        /// <param name="context">依赖注入的数据库上下文</param>
        public BaseDal(BaseDBContext context)
        {
            _context = context;
        }

        public T Add(T t)
        {
            _context.Set<T>().Add(t);
            return t;
        }

        public void Delete(T t)
        {
            _context.Set<T>().Remove(t);
        }
        public void DeleteBatch(List<T> list)
        {
            _context.Set<T>().RemoveRange(list);
        }

        public void Update(T t)
        {
            _context.Set<T>().Update(t);
        }


        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="whereLambda">Lambda条件表达式</param>
        /// <returns></returns>
        public IQueryable<T> GetModels(Expression<Func<T, bool>> whereLambda)
        {
            return _context.Set<T>().Where(whereLambda);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="type"></typeparam>
        /// <param name="pageSize">每页数量</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="isAsc">是否正序</param>
        /// <param name="orderByLambda">排序Lambda</param>
        /// <param name="whereLambda">条件Lambda</param>
        /// <returns></returns>
        public IQueryable<T> GetModelsByPage<type>(int pageSize, int pageIndex, bool isAsc, Expression<Func<T, type>> orderByLambda, Expression<Func<T, bool>> whereLambda)
        {
            if (isAsc)
            {
                return _context.Set<T>().Where(whereLambda).
                OrderBy(orderByLambda).
                Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
            else
            {
                return _context.Set<T>().Where(whereLambda).
                OrderByDescending(orderByLambda).
                Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }

        }

        public int SaveChanges()
        {
            return _context.SaveChanges();
        }

        public void Dispose()
        {
            //销毁上下文
            _context.Dispose();
        }

        
    }
}
